<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect,
  NDatePicker,
} from 'naive-ui'
import { format } from 'date-fns'
import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '仪器配置' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '项目',
  initForm: {
    num:1,
    interval:30
  },
  doCreate: api.createSettingInstrument,
  doUpdate: api.updateSettingInstrument,
  doDelete: api.deleteSettingInstrument,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  InstiumentData: [],
  CityData: [],
  upload: null,
  fileListLength: 0,
  dateOptions: [],
})
onMounted(() => {
  api.getSpaceList().then((res) => (data.CityData.value = res.data))
  api.getInstrumentList().then((res) => (data.InstiumentData.value = res.data))
  $table.value?.handleSearch()
})
function  level_format(level,data){
  let ret = ""
  if (data) {
    data.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  }
  
  return ret
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '门店',
    key: 'space_id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => level_format(row.space_id,data.CityData.value) }
      )
    },
  },
  {
    title: '仪器',
    key: 'instrument_id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
    render(row) {
      let num = row.instrument_id
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => level_format(num,data.InstiumentData.value) }
      )
    },
  },
  {
    title: '数量',
    key: 'num',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '时长',
    key: 'interval',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '可约日期',
    key: 'date',
    align: 'center',
    width: 200,
    render(row) {
      const dateValue = row.date ?? []
      const group = []
      for (let i = 0; i < dateValue.length; i++)
        group.push(
          h(
            NTag,
            { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
            { default: () => dateValue[i] }
          )
        )
      return h('span', group)
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
                if (!modalForm.value.files) {
                  modalForm.value.files = []
                }
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/contents/delete']]
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

const validateAddUser = {
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur'],
    },
  ],
}

async function addDepts() {
  handleAdd()
}

//处理多个日期

  const today = new Date()
  for (let i = 0; i < 30; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    data.dateOptions.push({ label: format(date, 'yyyy-MM-dd'), value: format(date, 'yyyy-MM-dd') })
  }

const upValuedate = (value) => {
  console.log(value, 'vvvvv')
  modalForm.value.date = value
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent>
      <CommonPage show-footer title="仪器列表">
        <template #action>
          <NButton
            v-permission="'post/api/content/contents/create'"
            type="primary"
            @click="addDepts"
          >
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建仪器
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getSettingInstrument"
          :scroll-x="1200"
        >
          <template #queryBar>
             <QueryBarItem label="门店" :label-width="70">
              <NSelect
                v-model:value="queryItems.space_id"
                style="width: 150px"
                :options="data.CityData.value"
                clearable
                placeholder="请选择门店"
              />
            </QueryBarItem>
            <QueryBarItem label="仪器" :label-width="70">
              <NSelect
                v-model:value="queryItems.instrument_id"
                style="width: 150px"
                :options="data.InstiumentData.value"
                clearable
                placeholder="请选择仪器"
              />
            </QueryBarItem>
          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 750px !important"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="90"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <NFlex justify="space-between">
              <NFormItem label="门店" path="space_id">
                <NSelect
                  style="width: 500px"
                  v-model:value="modalForm.space_id"
                  :options="data.CityData.value"
                  placeholder="请选择门店"
                />
              </NFormItem>
              <NFormItem label="仪器" path="instrument_id">
                <NSelect
                  style="width: 500px"
                  v-model:value="modalForm.instrument_id"
                  :options="data.InstiumentData.value"
                  placeholder="请选择仪器"
                />
              </NFormItem>
              <NFormItem label="时长(分钟)" path="interval">
                <NInputNumber
                  style="width: 200px"
                  v-model:value="modalForm.interval"
                  clearable
                  placeholder="输入时长(分钟)"
                />
              </NFormItem>
              <NFormItem label="数量" path="num">
                <NInputNumber
                  style="width: 200px"
                  v-model:value="modalForm.num"
                  clearable
                  placeholder="输入数量"
                />
              </NFormItem>
              <NFormItem label="可预约日期" path="date">
                <n-space align="center">
                  <n-select
                    style="width: 600px"
                    v-model:value="modalForm.date"
                    :options="data.dateOptions"
                    value-format="yyyy-MM-dd"
                    multiple
                    placeholder="选择多个日期"
                    @update-value="upValuedate"
                  />
                </n-space>
              </NFormItem>
            </NFlex>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
